package cn.hello2018.sdk.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author jeymingwu
 * @date 2019/5/8 15:55
 */
public class FileUploadUtil {

    private static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

    public static String uploadFile(MultipartFile file, String path) {
        String fileName = file.getOriginalFilename();
        // 文件拓展名
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID().toString() + "." + fileSuffix;
        logger.info("开始上传文件，上传文件的文件名为：{}，上传路径：{}，新文件名：{}", fileName, path, uploadFileName);

        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(path, uploadFileName);
        try {
            file.transferTo(targetFile);
//            // 文件上传到FTP服务器
//            FTPServerUtil.uploadFile(Lists.newArrayList(targetFile));
//            // 目标文件删除
//            targetFile.delete();
        } catch (Exception e) {
            logger.error("上传文件失败 ", e);
            return null;
        }
        return targetFile.getName();
    }
}
